<template>
  <div>
    <div class="search">
      <Row>
        <Col>
          <Card>
            <Row>
              <Form ref="searchForm" :model="searchForm" inline :label-width="100" class="search-form">
                <Form-item label="项目名称" prop="">
                  <Input v-model="searchForm.project_name" style="width: 260px;"/>
                </Form-item>
                <Form-item style="margin-left:-100px;" class="br">
                  <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                  <Button @click="handleReset">重置</Button>
                </Form-item>
              </Form>
            </Row>
            <Row class="operation">
              <Button @click="addBudget" type="primary" icon="md-add">添加工程预算</Button>
              <Button @click="editBudget" type="warning" icon="ios-bookmarks-outline" >编辑工程预算</Button>
              <Button @click="refresh" icon="refresh">刷新</Button>
            </Row>
            <Row>
              <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
              </Alert>
            </Row>
            <Row>
              <Table
                border
                :loading="loading"
                :columns="columns"
                :data="data"
                sortable="custom"
                @on-selection-change="showSelect"
                ref="table">
              </Table>
              <Table :columns="exportColumns" :data="exportData" ref="exportTable" style="display:none"></Table>
            </Row>
            <Row type="flex" justify="end" class="page">
              <Page
                :current="searchForm.pageNumber"
                :total="total"
                :page-size="searchForm.pageSize"
                @on-change="changePage"
                @on-page-size-change="changePageSize"
                :page-size-opts="[10,20,50]"
                size="small"
                show-total
                show-elevator
                show-sizer
              ></Page>
            </Row>
          </Card>
        </Col>
      </Row>
      <Modal v-model="budgetFormVisible" width="500" :title="modelTitle" :mask-closable='false'>
        <Form ref="budgetForm" :model="budgetForm" :label-width="100" :rules="budgetFormValidate">
          <FormItem label="项目名称" prop="project_id" class="margin-bottom-3" v-show="inserOrEdit">
            <Select v-model="budgetForm.project_id" clearable filterable style="width: 300px">
              <Option v-for="item in projectNameList" :value="item.id" :key="item.id">
                {{ item.project_name }}
              </Option>
            </Select>
          </FormItem>
          <FormItem label="预算设备费" prop="equipment_cost" class="margin-bottom-3">
            <Input v-model="budgetForm.equipment_cost" placeholder="请输入预算设备费（单位：元）" style="width: 260px"/>元
          </FormItem>
          <FormItem label="预算材料费" prop="material_cost" class="margin-bottom-3">
            <Input v-model="budgetForm.material_cost" placeholder="请输入预算材料费（单位：元）" style="width: 260px"/>元
          </FormItem>
          <FormItem label="预算总造价" prop="budget_cost" class="margin-bottom-3">
            <Input v-model="budgetForm.budget_cost" placeholder="请输入预算总造价（单位：元）" style="width: 260px"/>元
          </FormItem>
          <FormItem label="预算日期" prop="budget_date" class="margin-bottom-3">
            <DatePicker :value="budgetForm.budget_date" type="date" format="yyyy-MM-dd"
              placeholder="请选择日期" @on-change="getBudgetDate" style="width: 260px"></DatePicker>
          </FormItem>
          <FormItem label="预算书" prop="budget_content" class="margin-bottom-3" v-show="!inserOrEdit">
            <!-- <upload :defaultList="defaultList" :budgetId="budgetId" @on-uploaded="uploaded"/> -->
             <upload :budget="selectList[0]" @on-uploaded="uploaded"/>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="cancelBudget">取消</Button>
          <Button type="primary" :loading="submitLoading" @click="submitBudget">提交</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import { getProjectBudget, getNewBudgetProject, insertProjectBudget, updateProjectBudget, sendMessage } from '@/api/project';
import { base_url } from '@/libs/axios';
import util from '@/libs/util';
import upload from './upload';
export default {
  name: 'budget-manager',
  components: {
    upload
  },
  data() {
    return {
      loading: false,
      searchForm: {
        project_name: '',
        pageNumber: 1,
        pageSize: 10
      },
      data: [],
      total: 0,
      selectCount: 0,
      exportData: [],
      selectList: [],
      exportColumns: [],
      columns: [
        {
          type: "selection",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          title: '项目编号',
          key: 'project_code',
          width: 160,
          align: 'center'
        },
        {
          title: '项目名称',
          key: 'project_name',
          width: 220,
        },
        {
          title: '设备费(含税价)',
          key: 'equipment_cost',
          width: 120,
          align: 'right'
        },
        {
          title: '主材费(含税价)',
          key: 'material_cost',
          width: 120,
          align: 'right'
        },
        {
          title: '预算造价',
          key: 'budget_cost',
          width: 120,
          align: 'right'
        },
        {
          title: '预算员',
          key: 'real_name',
          width: 80,
          align: 'center'
        },
        {
          title: '编制日期',
          key: 'budget_date',
          width: 120,
          align: 'center'
        },
        {
          title: '预算书',
          key: 'budget_content',
          width: 60,
          align: 'center',
          render: (h, params) => {
            if (params.row.budget_content) {
              return h(
                "a",
                {
                  on: {
                    click: () => {
                      this.showDetail(params.row);
                    }
                  }
                },
                '预算书'
              );
            }
          }
        },
        {
          title: '短信通知',
          key: 'action',
          width: 180,
          align: 'center',
          render: (h, params) => {
            let reDisable = "通知了"+ params.row.message_count +"次";
            return h('div', [
              h('Button', {
                props: {
                  size: 'small',
                  type: 'success'
                },
                on: {
                  click: () => {
                    this.note(params.row)
                  }
                }
              }, reDisable)
            ]);
          }
        }
      ],
      projectNameList: [],
      budgetFormVisible: false,
      modelTitle: '',
      budgetForm: {},
      budgetFormValidate: {},
      submitLoading: false,
      inserOrEdit: true,
      defaultList: [],
    }
  },
  methods: {
    getBudgetList() {
      this.loading = true;
      getProjectBudget(this.searchForm).then(res => {
        this.loading = false;
        if (res.code === 0) {
          this.data = res.data.raws;
          this.total = res.data.count;
        }
      })
    },
    init() {
      this.getBudgetList();
    },
    handleSearch() {
      this.searchForm.project_name = this.searchForm.project_name.trim();
      if (this.searchForm.project_name.length > 0) {
        this.searchForm.pageNumber = 1;
        this.getBudgetList();
      } else {
        this.$Message.warning('请输入要搜索的项目名称！');
        return;
      }
    },
    handleReset() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getBudgetList();
    },
    addBudget() {
      const hasPermission = util.oneOf('add', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      this.budgetForm.project_id = 0;
      this.budgetForm.budget_date = '';
      this.budgetForm.equipment_cost = null;
      this.budgetForm.material_cost = null;
      this.budgetForm.budget_cost = null;
      delete this.budgetForm.id;
      delete this.budgetForm.budget_content;
      this.inserOrEdit = true;
      getNewBudgetProject().then(res => {
        if (res.code === 0) {
          this.projectNameList = res.data;
        }
      });
      this.modelTitle = '添加工程预算信息';
      this.budgetFormVisible = true;
    },
    editBudget() {
      const hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      if (this.selectList.length !== 1) {
        this.$Message.warning('必须选择一条记录进行操作!');
        return;
      }
      this.budgetForm.id = this.selectList[0].id;
      this.budgetForm.budget_date = this.selectList[0].budget_date;
      this.budgetForm.equipment_cost = this.selectList[0].equipment_cost;
      this.budgetForm.material_cost = this.selectList[0].material_cost;
      this.budgetForm.budget_cost = this.selectList[0].budget_cost;
      delete this.budgetForm.project_id;
      this.inserOrEdit = false;
      if (this.selectList[0].budget_content) {
        let params = {
          pic: `${base_url}/public/uploads/20200719/9a4c1ccf8a1244a9930a7072468699d9.jpg`,
          url: this.selectList[0].budget_content
        }
        this.defaultList.push(this.selectList[0].budget_content);
      } else {
        this.defaultList = [];
      }
      this.modelTitle = '编辑工程预算信息 - ' + this.selectList[0].project_name;
      this.budgetFormVisible = true;
    },
    refresh() {
      this.getBudgetList();
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    showSelect(e) {
      this.exportData = e;
      this.selectList = e;
      this.selectCount = e.length;
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getBudgetList();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getBudgetList();
    },
    showDetail(v) {
      if (v.budget_content) {
        window.open(`${base_url}/public/uploads/${v.budget_content}`);
      } else {
        this.$Message.info('请先上传预算书到系统中！');
        return
      }
    },
    getBudgetDate(v) {
      this.budgetForm.budget_date = v;
    },
    note(v) {
      if (v.message_count < 3) {
        let params = {
          mobile: v.mobile,
          name: v.contact,
          message: '电力安装项目预算共计' + v.budget_cost + '元'
        };
        sendMessage(params).then(res => {
          if (res.code === 0) {
            this.$Message.success(res.message);
            let params = {
              id: v.id,
              message_count: v.message_count + 1
            };
            updateProjectBudget(params).then(res => {
              this.getBudgetList()
            })
          }
        })
      } else {
        this.$Message.warning('通知短信发的已经很多了！');
        return;
      }
      
      
    },
    cancelBudget() {
      this.budgetFormVisible = false;
    },
    submitBudget() {
      this.$refs.budgetForm.validate(valid => {
        if (valid) {
          if (this.inserOrEdit) {
            this.submitLoading = true;
            insertProjectBudget(this.budgetForm).then(res => {
              this.submitLoading = false;
              if (res.code === 0) {
                this.$Message.success(res.message);
                this.refresh();
                this.budgetFormVisible = false;
              }
            })
          } else {
            this.submitLoading = true;
            delete this.budgetForm.project_id;
            updateProjectBudget(this.budgetForm).then(res => {
              this.submitLoading = false;
              if (res.code === 0) {
                this.$Message.success(res.message);
                this.refresh();
                this.budgetFormVisible = false;
              }
            })
          }
        }
      })
    },
    uploaded() {
      this.refresh;
    }
  },
  mounted() {
    this.init();
  }
}
</script>
<style lang="less" scoped>
@import "./budgetManager.less";
</style>